import React, {Component, PropTypes} from 'react'
import {Button, Card, Col, Form, Input, message, Modal, Popconfirm, Radio, Tabs, Tag} from 'antd'
import Info from './info/Info'
import BorrowRecord from '../../../common/components/users/BorrowRecord'
import CheckRecord from '../../../common/components/users/CheckRecord'
import PhoneRemarkRecord from '../../../common/components/users/PhoneRemarkRecord'
import AppLists from '../../../common/components/users/AppLists'
import Risk from './risk/Risk'
import Contacts from '../../photoCheck/common2/detail/info/Contacts'
import FacePhoto from '../../../common/components/users/Photos'
import OCR from '../../../common/components/users/OCR'
import KycAuthResult from './kyc/KycAuthResult'
import Relation from '../../../common/components/users/Relation'
import HighmarkReport from './highmark/HighmarkReport'
import Styles from './Index.less'
import {fetchPost} from '../../../../utils/request'

const TabPane = Tabs.TabPane
const FormItem = Form.Item
const CheckableTag = Tag.CheckableTag
const RadioGroup = Radio.Group

class UncontrolledCheckableTag extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      activity: props.activity
    }
  }

  componentWillReceiveProps(props) {
    if (props.activity != this.state.activity) {
      this.setState({
        activity: props.activity
      })
    }
  }

  handleChange(activity) {
    this.setState({
      activity: !this.state.activity
    })
    this.props.chooseTag(activity)
  };

  render() {
    return <CheckableTag checked={this.state.activity}
                         onChange={this.handleChange.bind(this)}>
      {this.props.tagName}
    </CheckableTag>
  }
}

class Detail extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      id: props.id,
      userId: props.userId,
      tradeNo: props.tradeNo,
      activeKey: (props.stepType == 'initialOrderRepeat'
        || props.stepType == 'initialOrderReupload'
        || props.stepType == 'initialOrderNew'
        || props.stepType == 'secondOrderVisit') ? 'contactRecord' : props.activeKey,
      item: props.item,
      showDetail: true,
      stepType: props.stepType,
      worksheetType: props.worksheetType,
      visible: false,
      processNode: props.processNode,
      tagData: [],
      tagIDs: {},
      managerInfo: {
        finish: '',
        remain: ''
      },
      currentType: '',
      areaIds: [],
      canReedit: false,
      mobileRedialAllow: props.mobileRedialAllow
    }

  }

  componentDidMount() {
    // console.log(111, this.state.item)
    this.getData()
  }

  getData() {
    let self = this
    if (this.state.userId != null) {
      function getTags() {
        return new Promise((resolve, reject) => {
          fetchPost(`/audit/usertag/${self.state.userId}/${self.state.processNode}/query`).then((res) => {
            if (res.code === 0) {
              if (res.data.list != null) {
                resolve(res)
              } else {
                reject('')
              }
            } else {
              message.error(res.msg)
              reject(res)
            }
          })
        })
      }

      // function getManagerInfo() {
      //   return new Promise((resolve, reject) => {
      //     fetchPost(`/audit/usertag/${self.state.userId}/query`).then((res) => {
      //       if(res.code === 0) {
      //         resolve(res)
      //       } else {
      //         message.error(res.msg)
      //         reject(res)
      //       }
      //     })
      //   })
      // }

      Promise.all([getTags()]).then((res) => {
        let [resTags, resManagerInfo] = [res[0], res[1]]
        resTags.data.list.forEach((value, index) => {
          value.childList.forEach((val, ind) => {
            if (value.type === 13) {
              this.state.areaIds.push(val)
            }
            if (val.activity) {
              this.state.tagIDs[val.tagId] = true
            }
          })
        })

        self.setState({
          tagData: resTags.data.list || [],
          managerInfo: {
            remain: '',
            finish: ''
          }
        })
      })
    }
  }

  componentWillReceiveProps(props) {
    if (this.state.id != props.id || this.state.userId != props.userId) {
      this.setState({
        id: props.id,
        activeKey: (props.stepType == 'initialOrderRepeat'
          || props.stepType == 'initialOrderReupload'
          || props.stepType == 'initialOrderNew'
          || props.stepType == 'secondOrderVisit') ? 'contactRecord' : props.activeKey,
        userId: props.userId,
        tradeNo: props.tradeNo,
        mobileRedialAllow: props.mobileRedialAllow,
        stepType: props.stepType,
        item: props.item
      }, () => {
        this.getData()
      })
    }
  }

  onChange(activeKey) {
    this.setState({activeKey})
  }

  areaOnChange(e) {
    this.state.areaIds.map((item) => {
      delete this.state.tagIDs[item.tagId]
    })
    this.state.tagIDs[e.target.value] = true
  }

  changeOrder(type, id) {
    this.props.changeOrder(type, id)
  }

  changeModal() {
    // fetchPost(`/audit/${this.state.item.userCode}/reedit/count`).then((json) => {
    //   if (json.code === 0) {
    //     this.setState({
    //       canReedit: json.data.canReedit,
    //       visible: !this.state.visible
    //     })
    //   } else {
    //     message.error(json.msg)
    //   }
    // })
    this.setState({
      visible: !this.state.visible
    })
  }

  operation(type) {
    this.setState({
      currentType: type
    }, () => {
      // this.state.currentType = type;
      console.log(this.state.currentType, 'this.state.currentType')
      let reason = this.props.form.getFieldValue('checkReason')
      let self = this
      let tagIdList = []
      for (let i in this.state.tagIDs) {
        tagIdList.push(i)
      }
      // 判断是否选择了城市区域
      let isChooseArea = false
      console.log(tagIdList)
      this.state.areaIds.map(item => {
        tagIdList.map(itemTag => {
          if (itemTag == item.tagId) {
            isChooseArea = true
          }
        })
      })

      if (this.state.processNode == '5' || this.state.processNode == '1') {
        isChooseArea = true;
      }

      // if (!isChooseArea) {
      //   message.info('Please choose the area')
      //   return false
      // }
      if (!reason && this.state.currentType == 'refuse') {
        message.info('Please enter the reason')
        return false
      }
      this.props.form.validateFields((errors, values) => {
        if (!errors) {
          let operationParams = {
            auditNo: this.state.id,
            message: reason,
            userCode: this.state.item.userCode,
            tradeNo: this.state.item.tradeNo,
            processNode: this.state.processNode,
            worksheetType: this.state.worksheetType,
            tagIdList
          }
          console.log(type);
          switch (type) {

            case 'pass':
              fetchPost('/audit/operate/pass', operationParams).then((json) => {
                if (json.code === 0) {
                  self.clearReason()
                  this.state.tagIDs = {}
                  self.changeOrder('pass', self.state.id)
                  message.success('Operate Success')
                } else {
                  message.error(json.msg)
                }
              })
              break

            case 'wait':
              fetchPost('/audit/operate/staging', operationParams).then((json) => {
                if (json.code === 0) {
                  self.clearReason()
                  self.changeOrder('wait', self.state.id)
                  this.state.tagIDs = {}
                  message.success('Operation Success')
                } else {
                  message.error(json.msg)
                }
              })
              break

            case 'refuse':
              fetchPost('/audit/operate/refuse', operationParams).then((json) => {
                if (json.code === 0) {
                  self.clearReason()
                  self.changeOrder('refuse', self.state.id)
                  this.state.tagIDs = {}
                  message.success('Operation Success')
                } else {
                  message.error(json.msg)
                }
              })
              break

            case 'reedit':
              fetchPost('/audit/operate/reedit', operationParams).then((json) => {
                if (json.code === 0) {
                  self.clearReason()
                  self.changeOrder('refuse', self.state.id)
                  this.state.tagIDs = {}
                  message.success('Operation Success')
                } else {
                  message.error(json.msg)
                }
              })
              break
            default:
          }
        }
      })
    })
  }

  operationV2(type) {
    this.setState({
      currentType: type
    }, () => {
      console.log(this.state.currentType, 'this.state.currentType')
      let self = this
      let reason = ''
      if (this.state.currentType == 'refuse') {
        reason = 'Unable to contact'
      }
      let operationParams = {
        auditNo: this.state.id,
        message: reason,
        userCode: this.state.item.userCode,
        tradeNo: this.state.item.tradeNo,
        processNode: this.state.processNode,
        worksheetType: this.state.worksheetType,
        tagIdList: []
      }
      switch (type) {
        case 'pass':
          fetchPost('/audit/operate/pass', operationParams).then((json) => {
            if (json.code === 0) {
              self.clearReason()
              this.state.tagIDs = {}
              self.changeOrder('pass', self.state.id)
              message.success('Operate Success')
            } else {
              message.error(json.msg)
            }
          })
          break

        case 'wait':
          fetchPost('/audit/operate/staging', operationParams).then((json) => {
            if (json.code === 0) {
              self.clearReason()
              self.changeOrder('wait', self.state.id)
              this.state.tagIDs = {}
              message.success('Operation Success')
            } else {
              message.error(json.msg)
            }
          })
          break

        case 'refuse':
          fetchPost('/audit/operate/refuse', operationParams).then((json) => {
            if (json.code === 0) {
              self.clearReason()
              self.changeOrder('refuse', self.state.id)
              this.state.tagIDs = {}
              message.success('Operation Success')
            } else {
              message.error(json.msg)
            }
          })
          break

        case 'reedit':
          fetchPost('/audit/operate/reedit', operationParams).then((json) => {
            if (json.code === 0) {
              self.clearReason()
              self.changeOrder('refuse', self.state.id)
              this.state.tagIDs = {}
              message.success('Operation Success')
            } else {
              message.error(json.msg)
            }
          })
          break
        default:
      }
    })
  }

  clearReason() {
    this.props.form.setFieldsValue({
      checkReason: ''
    })
    this.setState({
      visible: false,
      tagIDs: {}
    }, () => {
      this.getData()
    })
  }

  extraContent() {
    return (
      <span>
        {
          this.state.managerInfo.finish ? <span className='ml10'> 已完成:
              <span className='color-main'>
                {`${this.state.managerInfo.finish}单`}
              </span>
          </span>
            : ''
        }

        {
          this.state.managerInfo.remain ? <span className='ml10'> 剩余:
              <span className='color-main'>
                {`${this.state.managerInfo.remain}单`}
              </span>
          </span>
            : ''
        }

        <span className='ml10'> Loan ID: <span
          className='color-main'>{this.state.item.tradeNo || ''}</span></span>
        <span className='ml10 mr10'> Amount/Tenure：
          <span className='color-main'>
            {`${this.state.item.realCapital ||
            ''}₹ /${this.state.item.productDuration || ''}`}
          </span>
        </span>
        {
          this.state.stepType !== 'passOrder' &&
          this.state.stepType !== 'refuseOrder' &&
          this.state.stepType !== 'reeditOrder' &&
          this.state.stepType !== 'secondOrderVisit' &&
          this.state.stepType !== 'unAssignedOrder' &&
          this.state.userId ? <Button type='primary'
                                      onClick={this.changeModal.bind(
                                        this)}>Operate</Button>
            : null
        }
      </span>
    )
  }

  tabChangeCallback = (key) => {
    console.log(key, 'choose tab call back')
  }

  chooseTag(activity, id, name) {
    let self = this
    let form = this.props.form
    this.state.tagData.forEach((value, index) => {
      value.childList.forEach((val, ind) => {
        if (val.tagId == id) {
          val.activity = activity
        }
      })
    })

    this.setState({
      tagData: this.state.tagData || []
    })

    if (activity) {
      this.state.tagIDs[id] = true
      if (form.getFieldValue('checkReason')) {
        form.setFieldsValue({
          checkReason: `${self.props.form.getFieldValue('checkReason') + name};`
        })
      } else {
        form.setFieldsValue({
          checkReason: `${name};`
        })
      }
    } else {
      let beforeReason = self.props.form.getFieldValue('checkReason')
      let currentReason = beforeReason.replace(new RegExp(`${name};`, 'g'), '')
      form.setFieldsValue({
        checkReason: currentReason
      })
      delete this.state.tagIDs[id]
    }
  }

  showReeditButton() {
    if (this.state.processNode == '5') {
      return;
    }
    if (this.state.canReedit) {
      return <Popconfirm placement='top' title='Are you sure?'
                         onConfirm={() => {
                           this.operation('reedit')
                         }}>
        <Button type='default' className='ml10'>Reject-re-edit</Button>
      </Popconfirm>
    } else {
      return <Popconfirm placement='top' title='Are you sure?'
                         onConfirm={() => {
                           this.operation('reedit')
                         }}>
        <Button type='default' disabled className='ml10'>Reject-re-edit</Button>
      </Popconfirm>
    }
  }

  render() {
    const {getFieldDecorator} = this.props.form

    return (
      <div>
        <Modal visible={this.state.visible}
               onOk={this.clearReason.bind(this)}
               onCancel={this.clearReason.bind(this)}
               footer={null}
        >
          <Form>

            <FormItem className={Styles.operationHeader}>
              <span className={Styles.title}>Order operation</span><br/>


              {/*<Popconfirm placement='top' title='Are you sure?'*/}
              {/*            onConfirm={() => {*/}
              {/*              this.operation('pass')*/}
              {/*            }}>*/}
              {/*  <Button type='primary' className='' style={{width: '90px'}}>Pass</Button>*/}
              {/*</Popconfirm>*/}

              <Popconfirm placement='top' title='Are you sure?'
                          onConfirm={() => {
                            this.operation('refuse')
                          }}>
                <Button type='default' className='ml10' style={{width: '90px'}}>Refuse</Button>
              </Popconfirm>

              {this.state.stepType == 'initialOrderRepeat'
              || this.state.stepType == 'initialOrderReupload'
              || this.state.stepType == 'initialOrderNew'
              || this.state.stepType == 'secondOrderVisit' ?
                <Popconfirm placement='top' title='Are you sure?'
                            onConfirm={() => {
                              this.operation('wait')
                            }}>
                  {this.state.mobileRedialAllow != 1 ?
                    <Button type='default' className='ml10' disabled style={{width: '90px'}}>Postpone</Button> :
                    <Button type='default' className='ml10' style={{width: '90px'}}>Postpone</Button>}
                </Popconfirm>
                : null}
              {/*{this.showReeditButton()}*/}
            </FormItem>

            <FormItem>
              {getFieldDecorator('checkReason',
                {
                  rules: [{
                    required: this.state.currentType == 'refuse',
                    message: 'Please enter the reason'
                  }]
                })(
                <Input placeholder='Please enter the reason' className='mh150' type='textarea'/>
              )}
            </FormItem>
          </Form>
          {this.state.processNode == '5' || this.state.processNode == '1' ? "" :
            <Card noHovering title="User's area" className={Styles.partLeft}>
              <RadioGroup onChange={this.areaOnChange.bind(this)}>
                {
                  this.state.tagData.map((cate) => {
                    if (cate.type === 13) {
                      return cate.childList.map((tag) => (
                        <Radio value={tag.tagId}>{tag.name}</Radio>))
                    }
                  })
                }
              </RadioGroup>
            </Card>}
          <Tabs onChange={this.tabChangeCallback} type="card">
            <TabPane tab="Reason label" key="1">
              <Card noHovering>
                {
                  this.state.tagData.map((cate, index) => {
                    if (cate.type !== 13 && cate.type !== 14 && cate.type !== 15 && cate.type !== 16) {
                      return <div key={index}>

                        <span className='font13 color-main'>{cate.typeName}</span>:
                        <br/>
                        {
                          cate.childList.map((tag, index) => (
                            <UncontrolledCheckableTag
                              key={index}
                              chooseTag={(activity) => this.chooseTag(activity,
                                tag.tagId, tag.name)} tagName={tag.name}
                              activity={tag.activity}/>
                          ))
                        }
                      </div>
                    }
                  })
                }
              </Card>
            </TabPane>
            {/*<TabPane tab="Re-edit label" key="2">
              <Card noHovering>
                {
                  this.state.tagData.map((cate, index) => {
                    if (cate.type === 14 || cate.type === 15 || cate.type === 16) {
                      return <div key={index}>

                        <span className='font13 color-main'>{cate.typeName}</span>:
                        <br/>
                        {
                          cate.childList.map((tag, index) => (
                            <UncontrolledCheckableTag
                              key={index}
                              chooseTag={(activity) => this.chooseTag(activity,
                                tag.tagId, tag.name)} tagName={tag.name}
                              activity={tag.activity}/>
                          ))
                        }
                      </div>
                    }
                  })
                }
              </Card>
            </TabPane>*/}
          </Tabs>

        </Modal>

        <div className={Styles.hideScroll}>
          <Card bodyStyle={{padding: 0}} bordered={false} noHovering>
            <div className=''>
              {this.extraContent()}
              <Tabs className={Styles.tabs} activeKey={this.state.activeKey}
                    onChange={(e) => this.onChange(e)}>

                {this.state.stepType == 'initialOrderRepeat'
                || this.state.stepType == 'initialOrderReupload'
                || this.state.stepType == 'initialOrderNew'
                || this.state.stepType == 'telOrder'
                || this.state.stepType == 'telOrderRepeat'
                || this.state.stepType == 'secondOrderVisit'
                  ? null :
                  <TabPane tab='Information-Photo' key='detail'>
                    {
                      this.state.activeKey === 'detail'
                        ? <div className={Styles.tabsWrapper}>
                          <Col span={12}>
                            <Risk processNode={this.state.processNode} id={this.state.item} userId={this.state.userId}/>
                            <FacePhoto userId={this.state.userId} tradeNo={this.state.item.tradeNo}
                                       stepType={this.state.stepType}/>
                            {/*<OCR userId={this.state.userId} tradeNo={this.state.item.tradeNo}
                             stepType={this.state.stepType}/>*/}
                            <KycAuthResult userId={this.state.userId} tradeNo={this.state.item.tradeNo}
                                           stepType={this.state.stepType}/>
                          </Col>
                          <Col span={12}>
                            <Card title='' bodyStyle={{padding: '5px'}} noHovering>
                              <Info id={this.state.id}
                                    userId={this.state.userId}
                                    item={this.state.item}
                                    tradeNo={this.state.item.tradeNo}
                                    stepType={this.state.stepType}
                                    processNode={this.state.processNode}
                              />
                            </Card>
                          </Col>
                        </div>
                        : <span/>
                    }
                  </TabPane>
                }

                <TabPane tab='Phone Information' key='contactRecord'>
                  {
                    this.state.activeKey === 'contactRecord' ?
                      <div className={Styles.tabsWrapper}>
                        {
                          this.state.processNode == '3' || this.state.processNode == 'A' ?
                            <Contacts userId={this.state.userId} id={this.state.id} hideOther={'1'}/>
                            :
                            this.state.processNode == '1' ?
                              <Contacts userId={this.state.userId} id={this.state.id} showCategory={['1']}/>
                              : <Contacts userId={this.state.userId} id={this.state.id}/>
                        }
                        {/*{*/}
                        {/*  this.state.processNode == '1' || this.state.processNode == '3' ? null : <AppLists userId={this.state.userId}/>*/}
                        {/*}*/}
                        {
                          this.state.processNode == '1' || this.state.processNode == '3' || this.state.processNode == 'A' ?
                            <Info id={this.state.id}
                                  userId={this.state.userId}
                                  item={this.state.item}
                                  tradeNo={this.state.item.tradeNo}
                                  stepType={this.state.stepType}
                                  processNode={this.state.processNode}
                            />
                            : null
                        }
                        <Relation userId={this.state.userId} id={this.state.id}/>

                        <Popconfirm placement='top' title='Are you sure?'
                                    onConfirm={() => {
                                      this.operationV2('wait')
                                    }}>
                          {this.state.mobileRedialAllow != 1 ?
                            <Button type='default' className='ml10' disabled style={{width: '90px'}}>Postpone</Button> :
                            <Button type='primary' className='ml10' style={{width: '90px'}}>Postpone</Button>}
                        </Popconfirm>

                        {/*<Popconfirm placement='top' title='Are you sure?'*/}
                        {/*            onConfirm={() => {*/}
                        {/*              this.operationV2('refuse')*/}
                        {/*            }}>*/}
                        {/*  {this.state.mobileRedialAllow == 1 ?*/}
                        {/*    null :*/}
                        {/*    <Button type='primary' className='ml10' style={{width: '90px'}}>Refuse</Button>}*/}
                        {/*</Popconfirm>*/}
                      </div>
                      : <span/>
                  }
                </TabPane>

                <TabPane tab='Application History' key='records'>
                  {
                    this.state.activeKey === 'records'
                      ? <div className={Styles.tabsWrapper}>
                        <BorrowRecord userId={this.state.userId}/>
                        <PhoneRemarkRecord userId={this.state.userId}/>
                        <CheckRecord userId={this.state.userId} tradeNo={this.state.item.tradeNo}/>
                      </div>
                      : <span/>
                  }
                </TabPane>

                <TabPane tab='Highmark Report' key='highmarkReport'>
                  {
                    this.state.activeKey === 'highmarkReport' ?
                      <div className={Styles.tabsWrapper}>
                        <HighmarkReport tradeNo={this.state.tradeNo}/>
                      </div>
                      : <span/>
                  }
                </TabPane>

              </Tabs>
            </div>
          </Card>
          {/*<CheckRecord userId={this.state.userId} tradeNo={this.state.item.tradeNo}/>*/}
        </div>
      </div>
    )
  }
}

Detail = Form.create()(Detail)

export default Detail
